<template>
  <div class="lix-container">
    <div class="lix-pdt__header">
      <div class="lix-pdt__swipper">
        <swiper :indicator-dots="true" :autoplay="true" interval="5000" duration="1000" :circular="true" @change="swiperChange" @animationfinish="animationfinish">
          <div v-for="(item, index) in imgUrls" :key="index">
            <swiper-item @click="handleSwiper" :data-index="index">
              <image :src="item.src" class="slide-image"/>
            </swiper-item>
          </div>
        </swiper>
      </div>
      <div class="lix-pdt__info">
        <div class="title-view">
          <div class="title">{{ goodsinfo.title }}</div>
          <!-- <div class="share">
            <image src="../static/images/share.png" />
          </div> -->
        </div>
        <div class="desc"><span v-if="goodsinfo.slogan">「{{ goodsinfo.slogan }}」</span>{{ goodsinfo.description }}</div>
        <div class="price">
          <span class="unit">￥</span>{{ selectedSkuComb ? selectedSkuComb.price / 100 : goodsinfo.price / 100 }}
        </div>
      </div>
    </div>
    <div class="lix-pdt__content">
      <div class="option-container">
        <div class="section" @click="showSkuView">
          <div class="title">已选</div>
          <div class="value"><span v-if="selectedSkuComb">{{ selectedSkuComb.text }}</span></div>
          <div class="arrow"><image src="../static/images/arrow.png"/></div>
        </div>
        <div class="section tip-section">
          <div class="tips">
            <div class="icon"><image src="../static/images/check.png" /></div>
            <div class="text">7天无理由退货</div>
          </div>
          <div class="tips">
            <div class="icon"><image src="../static/images/check.png" /></div>
            <div class="text">15天质量问题换货</div>
          </div>
          <div class="tips">
            <div class="icon"><image src="../static/images/check.png" /></div>
            <div class="text">365天保修</div>
          </div>
        </div>
      </div>
      <div class="product-detail">
        <wxParse :content="goodsinfo.content" />
      </div>
    </div>
    <div class="lix-pdt__footer">
      <!-- <div class="like">
        <image src="../../static/images/liked.png" />
        喜欢
      </div> -->
      <div class="cart-container">
        <div class="cart" @click="go2Cart">
          <image src="../static/images/cart.png"/>
          购物车
        </div>
        <div class="bridge" v-if="cartNums.length > 0">{{ cartNums }}</div>
      </div>
      <div class="add">
        <button @click="onAddCart">加入购物车</button>
      </div>
    </div>
    <div class="lix-pdt__markview" v-if="showChoseSku">
      <div class="lix-pdt__chosesku">
        <div class="sku-container">
          <div class="header">
            <div class="img">
              <image :src="goodsinfo.picture" />
            </div>
            <div class="info">
              <div class="price">
                <span class="unit">￥</span>{{ selectedSkuComb.price / 100 }}
              </div>

              <div class="desc">{{ selectedSkuComb.text }}</div>
            </div>
            <div class="close" @click="closeSkuView">
              <image src="../static/images/close.png" />
            </div>
          </div>
          <div class="seperate"></div>
          <scroll-view scroll-y style="height: 518rpx;">
            <div class="color" v-for="(skuTreeItem, index) in skuTree" :key="index">
              <div>{{ skuTreeItem.k }}</div>
              <div class="color-container">
                <sku-row-item
                  v-for="(skuValue, valueIndex) in skuTreeItem.v"
                  :key="valueIndex"
                  :sku-key-str="skuTreeItem.k_s"
                  :sku-value="skuValue"
                  :sku-event-bus="skuEventBus"
                  :selected-sku="selectedSku"
                  :sku-list="sku.list"
                  @sku:select="onSelect"
                />
                <!-- <div class="color-item" v-for="(skuObj, index) in item.v" :key="index" @click="clickSkuItem" :data-k_s="item.k_s" :data-id="skuObj.id">
                  <SkuRow
                    :sku="skuObj"
                    :k_s="item.k_s"
                    :selectArray="selectArray"
                    :containsArray="containsArray"
                    :listArray="sku.list"
                  />
                </div> -->
              </div>
            </div>
            <div class="seperate"></div>
            <div class="count">
              购买数量
              <zan-stepper :stepper="stepper" :min="min" :max="max" componentId="stepper" size="small" @handleZanStepperChange="handleZanStepperChange"/>
            </div>
          </scroll-view>
        </div>
        <div class="lix-pdt__skufotter">
          <button @click="onAddCart">加入购物车</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getShopDataApi, addShopToCartApi } from '../api';
import ZanStepper from '../../node_modules/mpvue-zanui/src/components/zan/stepper';
import SkuRow from '../components/sku-row';
import Tip from '../utils/tips';
import wxParse from 'mpvue-wxparse';
import { isSkuChoosable, getSkuComb, isAllSelected } from '../utils/sku/skuHelper.js';
import SkuRowItem from '../components/SkuRowItem';
import { UNSELECTED_SKU_VALUE_ID } from '../utils/sku/constans';

export default {
  components: {
    ZanStepper,
    SkuRow,
    wxParse,
    SkuRowItem
  },
  data() {
    return {
      imgUrls: [],
      goodsinfo: {},
      sku: {},
      initialSku: {},
      selectedSku: {},
      selectedNum: 1,
      showChoseSku: false,
      stepper: 1,
      min: 1,
      max: 20,
      goodsId: null,
      cartNums: 0
    };
  },
  computed: {
    skuTree() {
      return this.sku.tree || [];
    },
    // 判断是否已经选择全部的sku
    isSkuCombSelected() {
      if (!this.sku.tree || !this.selectedSku) {
        return false;
      }
      return isAllSelected(this.sku.tree, this.selectedSku);
    },
    // 已经选择的商品
    selectedSkuComb() {
      if (!this.hasSku) {
        return {
          id: this.sku.collection_id,
          price: Math.round(this.sku.price * 100),
          stock_num: this.sku.stock_num
        };
      }
      if (this.isSkuCombSelected) {
        return getSkuComb(this.sku.list, this.selectedSku);
      }

      return null;
    },
    hasSku() {
      return !this.sku.none_sku;
    }
  },
  onLoad(option) {
    this.getShopData(option.id);
  },
  methods: {
    resetSelectedSku(skuTree) {
      this.selectedSku = {};
      // 重置selectedSku
      skuTree.forEach(item => {
        this.selectedSku[item.k_s] = this.initialSku[item.k_s] || UNSELECTED_SKU_VALUE_ID;
      });

      // 只有一个sku规格值时默认选中
      skuTree.forEach(item => {
        const key = item.k_s;
        const valueId = item.v[0].id;
        if (
          item.v.length === 1 &&
          isSkuChoosable(this.sku.list, this.selectedSku, {key, valueId})
        ) {
          this.selectedSku[key] = valueId;
        }
      });
      console.log(this.selectedSku);
      console.log('skucomb: ', this.selectedSkuComb);
    },
    getShopData(id) {
      getShopDataApi({id: id})
        .then(res => {
          console.log(res);
          const data = res.data;
          this.imgUrls = data.goodsinfo.album;
          this.goodsId = data.goods_id;
          this.goodsinfo = data.goodsinfo;
          this.initialSku = data.initialSku;
          this.initializeSkuTree(data.sku);
          this.cartNums = data.cartSkuCount;
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleZanStepperChange(e) {
      console.log(e);
      const {stepper} = e;
      this.stepper = stepper;
    },
    showSkuView() {
      console.log('click');
      this.showChoseSku = true;
    },
    closeSkuView() {
      this.showChoseSku = false;
    },
    initializeSkuTree(sku) {
      if (sku === 'undefined' || sku === null) {
        this.skuTree = null;
        return;
      }
      this.sku = sku;
      console.log('now tree is ', this.skuTree);
      this.resetSelectedSku(this.skuTree);
    },
    onSelect(skuValue) {
      console.log('skuValue: ----> ', skuValue);
      console.log('befor selectedSku: ------> ', this.selectedSku);
      // 点击已选中的sku时则取消选中
      this.selectedSku =
        this.selectedSku[skuValue.skuKeyStr] === skuValue.id
          ? { ...this.selectedSku, [skuValue.skuKeyStr]: UNSELECTED_SKU_VALUE_ID }
          : { ...this.selectedSku, [skuValue.skuKeyStr]: skuValue.id };

      // 原组件的emit函数
      console.log('skucomb: ', this.selectedSkuComb);
    },
    onAddCart() {
      const err = this.validateSku();
      if (err) {
        Tip.error(err);
        return;
      }

      console.log('可以加入购物车');
      addShopToCartApi({
        goods_id: this.selectedSkuComb.id,
        product_id: this.goodsId,
        nums: this.stepper
      })
        .then(res => {
          console.log(res);
          this.cartNums = res.data + '';
          this.closeSkuView();
          Tip.success('加入购物车成功');
        })
        .catch(e => {
          console.log(e);
        });
    },
    validateSku() {
      if (this.selectedNum === 0) {
        return '商品已经无法购买啦';
      }
      if (!this.isSkuCombSelected || this.selectedSkuComb === null) {
        return '请选择商品规格';
      }

      return false;
    },
    go2Cart(e) {
      wx.navigateTo({
        url: '/pages/cartForNavi'
      });
    }
  }
};
</script>

<style lang="scss">
@import "../theme-chalk/product.scss";
// rich-text {
//   width: 100%;
// }
.htmlcontainer img {
  width: 100%;
}
</style>
